<template>
  <div class="login-container" v-if="backImg">
    <img :src="logo" class="nav" v-if="false" />
    <el-form
      ref="ruleFormRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">{{ Name }}</h3>
      </div>
      <el-form-item prop="username" class="form_item">
        <el-input
          ref="username"
          v-model="loginForm.username"
          :placeholder="$t('login.name')"
          name="username"
          type="text"
          tabindex="1"
        >
          <template #prefix>
            <span class="svg-container">
              <SvgIcon icon-class="user1" />
            </span>
          </template>
        </el-input>
      </el-form-item>
      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password" class="form_item">
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            :placeholder="$t('login.password')"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter="handleLogin(ruleFormRef)"
          >
            <template #prefix>
              <span class="svg-container">
                <SvgIcon icon-class="password" />
              </span>
            </template>
            <template #suffix>
              <span class="show-pwd" @click="showPwd">
                <SvgIcon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-tooltip>
      <el-form-item class="form_item">
        <el-button
          :loading="loading"
          type="primary"
          style="width: 100%; margin-bottom: 30px"
          @click.prevent="handleLogin(ruleFormRef)"
        >
          {{ $t('login.login') }}
        </el-button>
      </el-form-item>
      <div style="position: relative">
        <div class="tips">
          <span>{{ $t('login.name') }}: admin</span>
          <span>{{ $t('login.password') }}: admin</span>
          <span class="i18n_tip">
            <SetI18n></SetI18n>
          </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup name="Login">
import SetI18n from '@/views/SetI18n'
import { BackgroundImageList, Name, logo } from '@/config'
import { FormInstance } from 'element-plus'
import { loginRules } from './unresponsiveData'
import { loginApi } from '@/api/Login'
import { LoginFormType } from '@/interfaces/LoginType/LoginType'
import { ResultType } from '@/mock/modules/Login'
import { useLoginStore } from '@/store/Login'
import { useRouterStore } from '@/store/Router'
/**
 * @return hooks
 * **/
const router = useRouter()
const store = useLoginStore()
const router_store = useRouterStore()
/**
 * @return {data||computed}
 * **/
let ruleFormRef = ref<FormInstance | null>(null)
const loginForm = reactive<LoginFormType>({
  username: 'admin', //用户名
  password: 'admin' //密码
})
const capsTooltip = ref<boolean>(false)
const loading = ref<boolean>(false)
const passwordType = ref<string>('password')
const backUrl = ref<string>(`wallhaven-j5y525.webp`)
const backImg = computed<string>(() => `url('/src/assets/images/${backUrl.value}')`)
const timeOutTime = reactive<{
  timeOut: NodeJS.Timeout | null
  time: number
}>({
  timeOut: null,
  time: 0
})
/**
 * @return {method}
 * **/
const checkCapslock = (e: KeyboardEvent) => {
  const { key } = e
  capsTooltip.value = (key && key.length === 1 && key >= 'A' && key <= 'Z') as boolean
}
const showPwd = () => {
  if (passwordType.value === 'password') {
    passwordType.value = ''
  } else {
    passwordType.value = 'password'
  }
}
const getRouter = async () => {
  const { user } = store
  await router_store.SETASYNCROUTER(user)
}
const loginSub = async () => {
  const res = await loginApi<LoginFormType, ResultType>(loginForm)
  const { message, result } = res
  store.SETTOKEN(result!)
  ElNotification({
    title: 'Success',
    message,
    type: 'success'
  })
  await getRouter()
  await router.push({ name: 'Home' })
}
const handleLogin = async (formEl: FormInstance | null) => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      loginSub()
    }
  })
}
onMounted(() => {
  timeOutTime.timeOut = setInterval(() => {
    timeOutTime.time++
    if (timeOutTime.time >= BackgroundImageList.length) {
      timeOutTime.time = 0
    }
    backUrl.value = BackgroundImageList[timeOutTime.time]
  }, 10000)
})
onUnmounted(() => {
  timeOutTime.timeOut && clearInterval(timeOutTime.timeOut)
})
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #409eff;
.login-container {
  min-height: 100vh;
  width: 100%;
  background-image: v-bind(backImg);
  /* 背景图垂直、水平均居中 */
  background-position: center center;
  /* 背景图不平铺 */
  background-repeat: no-repeat;
  /* 当内容高度大于图片高度时，背景图像的位置相对于viewport固定 */
  background-attachment: fixed;
  /* 让背景图基于容器大小伸缩 */
  background-size: cover;
  overflow: hidden;
  transition: all 1s;
  .login-form {
    position: relative;
    background: linear-gradient(90deg, #d2dbe5 25%, #2980b9 100%);
    width: 550px;
    max-width: 100%;
    height: 100% !important;
    padding: 40px 35px;
    margin: 245px auto 0;
    border-radius: 20px;
    box-shadow: 0 0 8px #bbb;
    overflow: hidden;
    :deep(.el-input__wrapper) {
      width: 98%;
      background: transparent;
      border: 0;
    }
    :deep(.el-input__inner) {
      color: #333;
    }
    .form_item {
      height: 15%;
    }
  }
  .i18n_tip {
    position: absolute;
    right: 0;
    bottom: 1px;
  }
  .tips {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    display: flex;
    padding: 10px 5px;
    color: $dark_gray;
    vertical-align: middle;
  }

  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .nav {
    position: absolute;
    width: 60px;
    height: 50px;
    left: 10px;
    top: 10px;
  }
}
</style>
